<template>
    <div class="app-detail">
        <el-card class="box-card">
            <div class="container-header">
                <div class="hign-line"></div>
                <div class="header-left">
                    {{$t('inventoryManagement.baseInfo')}}
                </div>
                <el-form :model="viewModel" ref="addForm" label-width="88px" :rules="rules">
                    <el-row :gutter="24" class="mb8">
                        <el-col :span="8">
                            <el-form-item :label="$t('inventoryManagement.inspectionBatchNo')" prop="inspectionLotMark">
                                <el-input v-model="viewModel.inspectionLotMark" disabled clearable size="small" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('inventoryManagement.inventoryQuantity')" prop="quantityAmount">
                                <el-input v-model="viewModel.quantityAmount" disabled clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('inventoryManagement.materialName')" prop="materialName">
                                <el-input v-model="viewModel.materialName" disabled clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('inventoryManagement.materialNo')" prop="materialCode">
                                <el-input v-model="viewModel.materialCode" disabled clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>

                        <!-- <el-col :span="8">
                            <el-form-item :label="$t('inventoryManagement.maturity')" prop="maturity">
                                <el-input v-model="viewModel.maturity" disabled clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col> -->
                        <el-col :span="8">
                            <el-form-item :label="$t('inventoryManagement.supplierNo')" prop="supplierCode">
                                <el-input v-model="viewModel.supplierCode" disabled clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('inventoryManagement.supplierName')" prop="supplierName">
                                <el-input v-model="viewModel.supplierName" disabled clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('inventoryManagement.batch')" prop="lot">
                                <el-input v-model="viewModel.lot" disabled clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="是否免检" prop="exempted">
                                <el-radio-group v-model="viewModel.exempted" :disabled="isView">
                                    <el-radio label="1">{{ $t("public.yes") }}</el-radio>
                                    <el-radio label="0">{{ $t("public.no") }}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="8">
                            <el-form-item label="有效期" prop="expireDate">
                                <el-date-picker format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" v-model="viewModel.expireDate" size="small" type="datetime" placeholder="选择日期时间">
                                </el-date-picker>
                            </el-form-item>
                        </el-col> -->

                    </el-row>

                </el-form>
            </div>
        </el-card>
        <div v-if="viewModel.exempted==='0'">
            <inspection-item-info ref="inspectSubmit" :itemData="inpectItemData" @callback="submitCallback" :isInventory="true" @copyVisible="templateVisible = true"></inspection-item-info>
        </div>

        <div class="submit-footer">
            <el-button icon="el-icon-close" size="small" @click="closeTab" class="drawer-close">{{$t('public.close')}}</el-button>
            <el-button type="primary" @click="saveStorage" :loading="loading" icon="el-icon-receiving" size="small">{{$t('public.saveStorage')}}</el-button>
            <el-button type="primary" v-if="!isView" @click="submitAddForm" :loading="loading" icon="el-icon-check" size="small">{{$t('public.submit')}}</el-button>
        </div>
        <copyInspectDataDialog :visible.sync="templateVisible" :viewModel="viewModel" v-if="templateVisible" @callback="(row)=>updateInspect(row)" />
    </div>

</template>

<script>
import {getType, refreshCache,} from '@/api/basic/dict/type'
import {listProject} from '@/api/basic/project'
import {listCheckoutUnit} from '@/api/basic/checkoutUnit'
import {addCheckInspection, getStock,} from '@/api/inventoryManagement/inspectedInventory'
import FileUploadInput from '@/components/FileUploadInput'
import MeasuringToolDialog from '@/views/components/MeasuringToolDialog'
import inspectionItemInfo from '@/views/components/InspectionItemInfo'
import copyInspectDataDialog from '../copyInspectData.vue'

export default {
    name: 'inspectionExemption',
    dicts: ['sys_normal_disable'],
    components: {
        FileUploadInput,
        MeasuringToolDialog,
        inspectionItemInfo,
        copyInspectDataDialog,
    },
    data() {
        return {
            direction: 'rtl',
            templateVisible: false,
            addInspectionExemption: false,
            drawer: false,
            approvalOpen: false,
            viewInspectionExemption: false,
            addType: 1,
            loading: false,
            stockList: [
                {
                    samplingOne: null,
                    samplingTwo: null,
                    samplingThree: null,
                    measuringTool: null,
                    inspectionType: '1',
                    specialCharacteristics: '0',
                    projectCode: null,
                },
            ],
            projectList: [],
            isView: this.$route.query.isView ? true : false,
            id: this.$route.params.id,
            frequencyOptions: [
                {
                    value: '批',
                    label: '批',
                },
                {
                    value: '件',
                    label: '件',
                },
                {
                    value: '年',
                    label: '年',
                },
                {
                    value: '季',
                    label: '季',
                },
                {
                    value: '月',
                    label: '月',
                },
                {
                    value: '日',
                    label: '日',
                },
            ],
            samplingSchemeOptions: [
                {
                    value: 'GB/T2828.1-2012',
                    label: 'GB/T2828.1-2012',
                },
                {
                    value: '百分比',
                    label: '百分比',
                },
                {
                    value: '固定抽样',
                    label: '固定抽样',
                },
                {
                    value: 'C=0',
                    label: 'C=0',
                },
            ],
            testMethodOptions: [
                {
                    value: '目测',
                    label: '目测',
                },
                {
                    value: '量具',
                    label: '量具',
                },
                {
                    value: '验证',
                    label: '验证',
                },
                {
                    value: 'ny-iqc作业指导书',
                    label: 'ny-iqc作业指导书',
                },
                {
                    value: '核对COA',
                    label: '核对COA',
                },
            ],
            samplingLevelOptions: [
                {
                    value: 'S-1',
                    label: 'S-1',
                },
                {
                    value: 'S-2',
                    label: 'S-2',
                },
                {
                    value: 'S-3',
                    label: 'S-3',
                },
                {
                    value: 'S-4',
                    label: 'S-4',
                },
                {
                    value: 'Ⅰ',
                    label: 'Ⅰ',
                },
                {
                    value: 'Ⅱ',
                    label: 'Ⅱ',
                },
                {
                    value: 'Ⅲ',
                    label: 'Ⅲ',
                },
            ],
            samplingMethodCOptions: [
                {
                    value: '0.01',
                    label: '0.01',
                },
                {
                    value: '0.015',
                    label: '0.015',
                },
                {
                    value: '0.025',
                    label: '0.025',
                },
                {
                    value: '0.04',
                    label: '0.04',
                },
                {
                    value: '0.1',
                    label: '0.1',
                },
                {
                    value: '0.15',
                    label: '0.15',
                },
                {
                    value: '0.25',
                    label: '0.25',
                },
                {
                    value: '0.4',
                    label: '0.4',
                },
                {
                    value: '0.65',
                    label: '0.65',
                },
                {
                    value: '1',
                    label: '1',
                },
                {
                    value: '1.5',
                    label: '1.5',
                },
                {
                    value: '4',
                    label: '4',
                },
                {
                    value: '6.5',
                    label: '6.5',
                },
                {
                    value: '10',
                    label: '10',
                },
            ],
            samplingLevelTypeOptions: [
                {
                    value: '正常',
                    label: '正常',
                },
                {
                    value: '放宽',
                    label: '放宽',
                },
                {
                    value: '加严',
                    label: '加严',
                },
            ],
            samplingFixedTypeOptions: [
                {
                    value: '批',
                    label: '批',
                },
                {
                    value: '件',
                    label: '件',
                },
            ],
            specialCharacteristicsOptions: [
                {
                    value: '空',
                    label: '空',
                },
                {
                    value: 'CC',
                    label: 'CC',
                },
                {
                    value: 'SC',
                    label: 'SC',
                },
            ],
            addModel: {},
            viewModel: {
                exempted: '0',
            },
            editModel: {},
            approvalForm: {
                status: '1',
                textarea: '',
            },
            unitList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                noticeTitle: undefined,
                noticeType: undefined,
                hasRead: undefined,
                createTime: undefined,
            },
            // 表单参数
            form: {},
            materialOptions: [],
            // 表单校验
            rules: {
                // expireDate: [
                //     {
                //         required: true,
                //         message: '有效期不能为空',
                //         trigger: 'change',
                //     },
                // ],
            },
            fullscreen: false,
            inpectItemData: [],
        }
    },
    created() {
        this.getStock()
        this.getProjectList()
        this.getMaterialType()
        this.getUnitList()
    },
    methods: {
        updateInspect(row) {
            this.inpectItemData = row.itemList
        },
        changeSampling(e, scope) {
            this.stockList[scope.$index].samplingTwo = null
            this.stockList[scope.$index].samplingThree = null
        },
        getUnitList() {
            listCheckoutUnit().then((res) => {
                this.unitList = res.rows
            })
        },
        changeProject(e) {
            let obj = this.projectList.find((item) => {
                return item.projectName === e.row.projectName
            })
            this.stockList[e.$index].projectCode = obj.projectCode
            this.stockList[e.$index].projectId = obj.projectId
        },
        getProjectList() {
            listProject().then((res) => {
                this.projectList = res.rows
            })
        },
        getMaterialType() {
            // listALLMaterialType().then((res) => {
            //     this.materialOptions = res.data
            // })
        },
        closeTab() {
            this.$router.go(-1)
        },
        effectDateChange(e, scope) {
            if (parseInt(e) > 0) {
                this.stockList[scope.$index].endDate = this.getNewDay(
                    scope.row.approvalTime,
                    e
                )
            }
        },
        getNewDay(dateTemp, days) {
            var dateTemp = dateTemp.split('-')
            //转换为MM-DD-YYYY格式
            var nDate = new Date(
                dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]
            )
            var millSeconds = Math.abs(nDate) + days * 24 * 60 * 60 * 1000
            var rDate = new Date(millSeconds)
            var year = rDate.getFullYear()
            var month = rDate.getMonth() + 1
            if (month < 10) month = '0' + month
            var date = rDate.getDate()
            if (date < 10) date = '0' + date
            return year + '-' + month + '-' + date
        },
        fileChange(e) {
            console.log(e)
        },
        drawerClose() {
            this.drawer = false
        },
        /** 查询字典类型列表 */
        getStock() {
            getStock(this.id).then((res) => {
                let viewModel = res.data
                if (viewModel.exempted !== '1') {
                    viewModel.exempted = '0'
                }

                this.viewModel = viewModel
                this.inpectItemData = res.data.checkItemList
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                dictId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.stockList.push({
                samplingOne: null,
                samplingTwo: null,
                samplingThree: null,
                measuringTool: null,
                inspectionType: '1',
                specialCharacteristics: '0',
                projectCode: null,
            })
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.dictId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const dictId = row.dictId || this.ids
            getType(dictId).then((response) => {
                this.form = response.data
                this.open = true
                this.title = '修改字典类型'
            })
        },
        /** 提交按钮 */
        submitAddForm: function () {
            this.addType = 1
            if (this.viewModel.exempted === '1') {
                this.submitCallback([])
            } else {
                if (this.submitForm()) {
                    this.$refs.inspectSubmit.submitAddForm()
                }
            }
        },
        saveStorage() {
            this.addType = 0
            if (this.viewModel.exempted === '1') {
                this.submitCallback([])
            } else {
                if (this.submitForm()) {
                    this.$refs.inspectSubmit.submitAddForm()
                }
            }
        },
        submitForm: function () {
            let isTrue = false
            this.$refs['addForm'].validate((valid) => {
                if (valid) {
                    isTrue = true
                } else {
                    this.$modal.msgError(this.$t('formValidation.theBasicInformationIsIncomplete'))
                    isTrue = false
                }
            })
            return isTrue
        },
        formatTargetValueForward(targetValue) {
            if (
                Object.prototype.toString.call(targetValue) !==
                '[object String]'
            ) {
                return ''
            }
            return targetValue.replace(/<|>|&/g, function (match) {
                return {
                    '<': '&lt;',
                    '>': '&gt;',
                    '&': '&amp;',
                }[match]
            })
        },
        submitCallback(params) {
            let typeList = [...params]
            typeList.forEach((io) => {
                io.targetValue = this.formatTargetValueForward(io.targetValue)
            })
            let submitData = {
                ...this.viewModel,
                checkItemList: params,
                isIncomingInspection: this.addType,
            }
            this.loading = true
            console.log(JSON.stringify(submitData))
            addCheckInspection(submitData)
                .then((response) => {
                    if (response.code == 200) {
                        this.$modal.msgSuccess('提交成功!')
                        this.$router.go(-1)
                    } else {
                        this.$modal.msgError(response.msg)
                        this.loading = false
                    }
                })
                .catch((error) => {
                    this.loading = false
                })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            if (this.stockList.length === 1) {
                this.$modal.msgWarning('请至少保留一条检验项!')
                return
            }
            this.stockList.splice(row.$index, 1)
        },
        /** 查看按钮操作 */
        handleView(row) {
            this.form = row
            this.viewInspectionExemption = true
            //   if(row.hasRead == 0){
            //     readNotice(row.noticeId).then(res=>{
            //       if(res.code == 200){
            //         this.handleQuery()
            //       }
            //     })
            //   }
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.drawer = true
        },
        /** 关闭抽屉操作 */
        handleClose(row) {
            this.drawer = false
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'system/dict/type/export',
                {
                    ...this.queryParams,
                },
                `type_${new Date().getTime()}.xlsx`
            )
        },
        /** 刷新缓存按钮操作 */
        handleRefreshCache() {
            refreshCache().then(() => {
                this.$modal.msgSuccess('刷新成功')
            })
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep .el-card {
    padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    float: left;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    line-height: 40px;
    display: flex;
    justify-content: center;
}
.header-right {
    float: right;
}
.container-header {
    float: left;
    width: 100%;
    border-bottom: 1px solid #ededf2;
    padding-left: 12px;
}
.container-table {
    float: left;
    margin-top: 6px;
    width: 100%;
    // max-height: calc(100vh - 600px);
    overflow: auto;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.hign-line {
    position: relative;
    left: -8px;
    top: 14px;
    height: 12px;
    border-radius: 2px;
    border: 1px solid #0b7be3;
    float: left;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}
.submit-footer {
    height: 52px;
    background: #ffffff;
    box-shadow: 0px -5px 5px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px 4px 0px 0px;
    position: fixed;
    z-index: 9;
    bottom: 0px;
    width: 100%;
    left: 0px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.samplingPercent {
    position: absolute;
    z-index: 9;
    right: 20px;
}
::v-deep .el-card {
    padding-top: 0px;
}
::v-deep .el-form-item {
    margin-bottom: 3px !important;
}
.app-detail {
    max-height: calc(100vh - 180px);
    overflow: auto;
}
</style>
